package uit.shoeshop.action;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import uit.shoeshop.dto.ProductDTO;
import uit.shoeshop.lib.Constants;
import uit.shoeshop.lib.Util;
import uit.shoeshop.model.SearchModel;

import com.opensymphony.xwork2.ActionSupport;
public class SearchAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	private ArrayList<ProductDTO> searchProduct;
	private String search_query;
	private int page;
	private String pagination;
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
    public String execute() throws Exception {
    	SearchModel search = new SearchModel();
    	try{
    		setSearchProduct(search.getAllProductbyKeyword(getSearch_query().replace(" ", "%"), getPage()==0?1:getPage()));
    		setPagination(Util.Panigation("/shoeshop/search.html?search_query="+getSearch_query()+"&page=", search.countTotalProduct(getSearch_query().replace(" ", "%")), Constants.LIMIT_CATEGORY, getPage()==0?1:getPage()));
    	}catch(Exception e){
    		return ERROR;
    	}finally{
    		search = null;
    	}
        return SUCCESS;
    }

	public void setSearchProduct(ArrayList<ProductDTO> searchProduct) {
		this.searchProduct = searchProduct;
	}

	public ArrayList<ProductDTO> getSearchProduct() {
		return searchProduct;
	}

	public void setSearch_query(String search_query) {
		this.search_query = search_query;
	}

	public String getSearch_query() {
		this.search_query = Util.del_space(this.search_query.trim());
		return search_query;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPage() {
		return page;
	}

	public void setPagination(String pagination) {
		this.pagination = pagination;
	}

	public String getPagination() {
		return pagination;
	}	
}
